package com.yztc.ui.details;

import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yztc.bean.details.MstjBean;
import com.yztc.bean.details.ProductDetailBean;
import com.yztc.bean.details.ProductImgBean;
import com.yztc.bean.details.ProductInfoBean;
import com.yztc.bean.details.ProductQualityBean;
import com.yztc.bean.details.ProductStyleBean;
import com.yztc.bean.details.ReviewBean;
import com.yztc.chunboapp.R;
import com.yztc.ui.details.adapter.DetailsBaseAdapter;
import com.yztc.ui.home.adapter.DetailsPagerAdapter;
import com.yztc.utils.FlowLayout;
import com.yztc.utils.ImageHelper;
import com.yztc.utils.MyListView;
import com.yztc.utils.ShareLog;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by My on 2016/10/9.
 */
public class DetailsActivity extends AppCompatActivity implements DetailsConstact.IDetailsView{
    //传递的productId
    private int mProductId;
    //传递的打折价格
    private String mDiscountPrice;
    //存放轮播图片的集合
    private List<ImageView> mImageViews;
    //存放跟随轮播动的小圆点
    private List<ImageView> icons;
    //轮播
    private ViewPager mVPLunBo;
    //小圆点的父布局
    private LinearLayout mLinearlayout;
    //presecter
    private DetailsPresenter detailsPresenter;
    //产品标题和价格等
    private TextView mTVShortName,mTVSubName,mTVMarketPrice,mTVChunBoPrice;
    //抢购图标 春播安心度图标,我的优点的图片
    private ImageView mIVQiangGou,mIVTag;
    //产品规格,流式布局
    private FlowLayout mFlowLayout;
    //买手推荐
    private TextView mTVRecommend;
    //我的优点,
    private TextView mTVAbout1,mTVAbout2,mTVAbout3;
    //我的详情
    private TextView mTVSpecifications,mTVProducingArea,mTVStorageMethod;
    //我的优点图片
    private LinearLayout mLineTpic;
    //你还要知道
    private LinearLayout mLineZhiDao;
    //评论
    private MyListView mLVReView;
    //评论人数
    private TextView mTVCommend;
    //导航 分享
    private ImageButton mIBtnShare;
    //轮播
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //跳转到下一个界面
            if (msg.what == 1) {
                int index = msg.arg1;
                mVPLunBo.setCurrentItem(index);
            }
        }
    };
    @Override
    protected void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_details);
        initView();
        //接收传递的产品productId
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        mProductId = Integer.parseInt(bundle.getString("product_id"));
        mDiscountPrice = bundle.getString("discount_price");
        //创建presenter
        detailsPresenter = new DetailsPresenter(this,mProductId);
        detailsPresenter.getLoadData();
        //设置监听
        setOnClickListener();
    }

    private void setOnClickListener() {
        //点击分享
        mIBtnShare.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                new ShareLog(DetailsActivity.this,"分享内容");
            }
        });
    }

    private void initView() {
        mVPLunBo = (ViewPager) findViewById(R.id.vp_details_lunbo);
        mLinearlayout = (LinearLayout) findViewById(R.id.line_details_lunbo);
        mTVShortName = (TextView) findViewById(R.id.tv_details_shortname);
        mTVSubName = (TextView) findViewById(R.id.tv_details_subname);
        mTVMarketPrice = (TextView) findViewById(R.id.tv_market_price);
        mTVChunBoPrice = (TextView) findViewById(R.id.tv_chunbo_price);
        mFlowLayout = (FlowLayout) findViewById(R.id.flow_detais);
        mIVQiangGou = (ImageView) findViewById(R.id.iv_details_qiangGou);
        mIVTag = (ImageView) findViewById(R.id.iv_tag_icon);
        mTVRecommend = (TextView) findViewById(R.id.tv_breason);
        mTVAbout1 = (TextView) findViewById(R.id.tv_about1);
        mTVAbout2 = (TextView) findViewById(R.id.tv_about2);
        mTVAbout3 = (TextView) findViewById(R.id.tv_about3);
        mLineTpic = (LinearLayout) findViewById(R.id.line_tpic);
        mTVSpecifications = (TextView) findViewById(R.id.tv_specifications);
        mTVProducingArea = (TextView) findViewById(R.id.tv_producing_area);
        mTVStorageMethod = (TextView) findViewById(R.id.tv_storage_method);
        mLineZhiDao = (LinearLayout) findViewById(R.id.line_zhidao);
        mLVReView = (MyListView) findViewById(R.id.lv_details);
        mTVCommend = (TextView) findViewById(R.id.tv_commend);
        mIBtnShare = (ImageButton) findViewById(R.id.ibtn_details_share);
    }

    DetailsPagerAdapter adapter;

    //view的回调，返回广告轮播数据
    @Override
    public void onLunBoData(List<ProductImgBean> productImgBeanList) {
        if (productImgBeanList != null && productImgBeanList.size() != 0){
            //获取viewpager的图片
            mImageViews = new ArrayList<>();
            for (int i=1;i<=productImgBeanList.size()*2;i++){
                ImageView iv = new ImageView(this);
                iv.setAdjustViewBounds(true);
                iv.setScaleType(ImageView.ScaleType.FIT_XY);
                ImageHelper.getNormalImage(this, productImgBeanList.get((productImgBeanList.size()*2)%i).getUrl(),iv);
                mImageViews.add(iv);
            }
            //调用初始化轮播小圆点集合的方法
            initIcons();
            //实现轮播的方法
            showLunBo();
            //重新提交数据，进行适配
            if(adapter==null) {
                adapter = new DetailsPagerAdapter(mImageViews);
                mVPLunBo.setAdapter(adapter);
            }else {
            adapter.setImageViews(mImageViews);
            }
        }
    }

    //实现轮播的方法
    private void showLunBo() {
        //解决ViewPager第一次不能向左滑动的小bug
        mVPLunBo.setCurrentItem(1000 *mImageViews.size());
        //设置ViewPager的界面切换监听方法
        mVPLunBo.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {

                //设置小圆点的切换
                for (int i = 0; i < icons.size(); i++) {
                    icons.get(i).setImageResource(R.mipmap.toudi);
                    if (i ==  position % mImageViews.size()){
                        icons.get(i).setImageResource(R.mipmap.green);
                    }
                }
            }
        });
        //开始线程任务
        final AutoRunTask autoTask = new AutoRunTask();
        autoTask.startRun();

        //处理ViewPager的触摸事件
        mVPLunBo.setOnTouchListener(new View.OnTouchListener() {
            //当触摸屏幕的时候调用
            //MotionEvent:手指触摸到屏幕的时候,所触发的一系列的事件.
            //down,up,move,cancle.
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                //当手指触摸到ViewPager的时候,ViewPager的自动跳转会停止;
                //如果手指没有触摸ViewPager,ViewPager的自动跳转又会开始.
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN://第一个被执行的事件
                        autoTask.stopRun();
                        break;
                    case MotionEvent.ACTION_CANCEL:
                    case MotionEvent.ACTION_UP:
                       autoTask.startRun();
                        break;
                }
                //此处只能返回false
                return false;
            }
        });
    }

    //自定跳转的线程任务【轮播】
    class AutoRunTask implements Runnable {
        private int delayTime = 2000;
        private boolean isStart = false;
        //开始线程任务
        public void startRun() {
            if (!isStart) {
                //关闭之前所有正在执行的任务
                mHandler.removeCallbacks(this);
                isStart = true;
                mHandler.postDelayed(this, delayTime);
            }
        }

        //停止线程的方法【轮播】
        public void stopRun() {
            if (isStart) {
                isStart = false;
                mHandler.removeCallbacks(this);
            }
        }

        @Override
        public void run() {
            int currentItem = mVPLunBo.getCurrentItem();
            //发送消息
            Message msg = Message.obtain();
            msg.what = 1;
            msg.arg1 = ++currentItem;
            mHandler.sendMessage(msg);
            //递归调用自身,形成循环.
            mHandler.postDelayed(this, delayTime);
        }
    }

    //初始化轮播小圆点
    public void initIcons(){
        mLinearlayout.removeAllViews();
        icons = new ArrayList<>();
        for (int i=0;i<mImageViews.size();i++){
            ImageView iv = new ImageView(this);
            iv.setImageResource(R.mipmap.toudi);
            //动态设置imageView的尺寸
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(55,55);
            iv.setLayoutParams(params);
            //动态设置imageView的间距
            iv.setPadding(30,1,1,30);
            mLinearlayout.addView(iv);
            icons.add(iv);
        }
        icons.get(0).setImageResource(R.mipmap.green);
    }

   //View的回调，接收网络获取错误信息
    @Override
    public void onFailLoadData(Throwable throwable) {
        Toast.makeText(this, throwable.toString(),Toast.LENGTH_LONG).show();
    }

    //view的回调，获取标题等数据
    @Override
    public void onTitleData(ProductInfoBean productInfoBean) {
      //展示数据
        if (productInfoBean != null){
            mTVShortName.setText(productInfoBean.getShortname());
            mTVSubName.setText(productInfoBean.getSubname());
            if (mDiscountPrice == null){
                mTVChunBoPrice.setText("¥"+productInfoBean.getChunboPrice());
            }else{
                mTVMarketPrice.setText("¥"+mDiscountPrice);
                mTVChunBoPrice.setText("¥"+productInfoBean.getChunboPrice());
                mTVChunBoPrice.getPaint()
                        .setFlags(Paint.STRIKE_THRU_TEXT_FLAG );
                mIVQiangGou.setImageResource(R.mipmap.xsqg);

            }
        }
    }

    //view的回调，获取产品规格数据
    @Override
    public void onGuiGeData(final List<ProductStyleBean> productStyle) {
        mFlowLayout.removeAllViews();
        if (productStyle != null && productStyle.size() != 0){
            for (int i=0;i<productStyle.size();i++){
                final Button button = new Button(this);
                button.setBackground(null);
                //设置button的字体颜色
                button.setTextColor(getResources().getColor(R.color.btn_details_text));
               //设置button的样式
                button.setBackgroundResource(R.drawable.shopping_longin_anniu);
                button.setPadding(30,3,30,3);
                button.setText(productStyle.get(i).getPropertyOptionNameAll());
                mFlowLayout.addView(button);
            }

        }
    }

   //view的回调，获取春播安心度的数据
    @Override
    public void onAnXinData(List<ProductQualityBean> productQuality) {
         if (productQuality != null && productQuality.size()!= 0){
             ImageHelper.getNormalImage(this,productQuality.get(0).getTagIcon(),mIVTag);
         }
    }

    //view的回调，获取买手推荐、我的优点等数据
    @Override
    public void onProductDetailsData(MstjBean mstj) {
        if (mstj != null ){
            //评价
            mTVRecommend.setText(mstj.getBreason());
            //3条我的优点内容
            mTVAbout1.setText(mstj.getAbout1());
            mTVAbout2.setText(mstj.getAbout2());
            mTVAbout3.setText(mstj.getAbout3());

            mLineTpic.removeAllViews();
            //我的优点的图片
            String imageBaseUrl = "http://i3.chunboimg.com/";
            if (mstj.getTpic700() != null && mstj.getTpic700().size() != 0){
                for (int i=0;i<mstj.getTpic700().size();i++){
                    String imageUrl = imageBaseUrl+mstj.getTpic700().get(i);
                    ImageView iv = new ImageView(this);
                    iv.setAdjustViewBounds(true);
                    ImageHelper.getNormalImage(this,imageUrl,iv);
                    mLineTpic.addView(iv);
                }
            }
        }
    }

    //view的回调，获取我的详情数据
    @Override
    public void onMyDetailsData(ProductDetailBean productDetailBean) {
       if (productDetailBean != null){
           mTVSpecifications.setText("规格:"+productDetailBean.getSpecifications());
           mTVProducingArea.setText("产地:"+productDetailBean.getProducingArea());
           mTVStorageMethod.setText("储存方法:"+productDetailBean.getStorageMethod());
       }
    }

    //view的回调，获取你还要知到的数据
    @Override
    public void onWxts1Data(List<String> wxts1) {
        mLineZhiDao.removeAllViews();
       if (wxts1 != null && wxts1.size() != 0){
           for (int i=0;i<wxts1.size();i++){
               TextView tv = new TextView(this);
               tv.setText(i+1+"."+wxts1.get(i));
               tv.setPadding(25,5,15,5);
               mLineZhiDao.addView(tv);
           }
       }
    }

    //view的回调，获取评论数据
    @Override
    public void onPingLunData(ReviewBean reviewBean) {
        DetailsBaseAdapter adapter = null;
        if (reviewBean != null){
            mTVCommend.setText(reviewBean.getTotal()+"人评论");
            adapter = new DetailsBaseAdapter(this,reviewBean.getList());
            mLVReView.setAdapter(adapter);
        }
    }
}

